import { GetCookie } from "./utils.js";
import { InitHeader } from "./header.js";

async function GetSignStat(access_token) {
  fetch(
    `http://localhost:9966/user/stat?access_token=${encodeURIComponent(
      access_token
    )}`,
    {
      method: "GET",
    }
  )
    .then((response) => response.json())
    .then((data) => {
      // 在页面上显示签到状态
      OnGetStat(data);
    })
    .catch((error) => console.error("Error fetching sign stat:", error));
}

async function Signin(access_token) {
  const pbody = `access_token=${encodeURIComponent(
    access_token
  )}&report_flag=1`;
  fetch(`http://localhost:9966/time/report`, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: pbody,
  })
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("签到失败");
      }
    })
    .then((data) => {
      if (data.retcode === 0) {
        OnSignIn(data); // 调用签到函数
      } else {
        alert("签到失败，请稍后再试");
      }
    })
    .catch((error) => {
      console.error("Error during signin:", error);
      alert("签到请求失败，请检查网络连接");
    });
}

async function Signout(access_token) {
  const pbody = `access_token=${encodeURIComponent(
    access_token
  )}&report_flag=2`;
  fetch(`http://localhost:9966/time/report`, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: pbody,
  })
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("签退失败");
      }
    })
    .then((data) => {
      if (data.retcode === 0) {
        OnSignOut(data); // 调用签退函数
      } else {
        alert("签退失败，请稍后再试");
      }
    })
    .catch((error) => {
      console.error("Error during signout:", error);
      alert("签退请求失败，请检查网络连接");
    });
}

function SigninFunc() {
  console.log("Signin Click!!!");
  Signin(GetCookie("access_token"));
}

function OnSignIn(response) {
  if (response.retcode != 0) {
    alert("签到失败，请稍后再试");
  }
  const signin_btn = document.getElementById("signin_btn");
  const signout_btn = document.getElementById("signout_btn");
  const dt = new Date(response.data.timestamp * 1000);
  const hours = String(dt.getHours()).padStart(2, "0");
  const minutes = String(dt.getMinutes()).padStart(2, "0");
  const seconds = String(dt.getSeconds()).padStart(2, "0");

  const formatted = `已签到 - ${hours}:${minutes}:${seconds}`;
  signin_btn.textContent = formatted;
  signin_btn.disabled = true;
  signout_btn.classList.toggle("d-none");
  GetSignStat(GetCookie("access_token")); // 重新获取签到状态
}

function SignoutFunc() {
  const signin_btn = document.getElementById("signin_btn");
  const signout_btn = document.getElementById("signout_btn");
  if (signin_btn.disabled != true) {
    alert("请先签到！");
    return;
  }
  Signout(GetCookie("access_token"));
  signout_btn.disabled = true; // 禁用签退按钮
  signout_btn.textContent = "正在签退..."; // 更新按钮文本
}

function OnSignOut(response) {
  const signout_btn = document.getElementById("signout_btn");
  if (response.retcode != 0) {
    signout_btn.disabled = false; // 启用签退按钮
    signout_btn.textContent = "签退"; // 恢复按钮文本
    alert("签退失败，请稍后再试");
    return;
  }
  const now = new Date(response.data.timestamp * 1000);
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  const formatted = `已签退 - ${hours}:${minutes}:${seconds}`;
  signout_btn.textContent = formatted;
  signout_btn.disabled = true;

  GetSignStat(GetCookie("access_token")); // 重新获取签到状态
}

function OnGetStat(data) {
  if (data.retcode !== 0) {
    console.error("获取签到状态失败:", data.retcode);
    alert("获取签到状态失败，请稍后再试");
    return;
  }
  const stat = data.stat;
  if (!stat) {
    console.error("签到状态数据格式错误");
    alert("签到状态数据格式错误，请稍后再试");
    return;
  }
  const second_per_hour = 3600;
  const miss_count = document.getElementById("miss_count");
  miss_count.textContent = stat.month_miss_days || 0; // 如果没有miss_count，默认为0
  const week_count = document.getElementById("week_count");
  week_count.textContent = stat.week_signed_days || 0; // 如果没有week_count，默认为0
  const week_time = document.getElementById("week_time_h");
  const week_time_m = document.getElementById("week_time_m");
  week_time_m.textContent = Math.floor((stat.week_total_time % second_per_hour) / 60) || 0; // 如果没有week_time_m，默认为0
  week_time.textContent = Math.floor(stat.week_total_time / second_per_hour) || 0; // 如果没有week_time，默认为0
  const month_count = document.getElementById("month_count");
  month_count.textContent = stat.month_signed_days || 0; // 如果没有month_count，默认为0
  const month_time = document.getElementById("month_time_h");
  const month_time_m = document.getElementById("month_time_m");
  month_time_m.textContent = Math.floor((stat.month_total_time % second_per_hour) / 60) || 0; // 如果没有month_time_m，默认为0
  month_time.textContent = Math.floor(stat.month_total_time / second_per_hour) || 0; // 如果没有month_time，默认为0
  const signin_btn = document.getElementById("signin_btn");
  const signout_btn = document.getElementById("signout_btn");

  if (stat.signin_time) {
    const dt = new Date(stat.signin_time * 1000);
    const hours = String(dt.getHours()).padStart(2, "0");
    const minutes = String(dt.getMinutes()).padStart(2, "0");
    const seconds = String(dt.getSeconds()).padStart(2, "0");

    const formatted = `已签到 - ${hours}:${minutes}:${seconds}`;
    signin_btn.textContent = formatted;
    signin_btn.disabled = true; // 禁用签到按钮
    if (signout_btn.classList.contains("d-none")) {
      signout_btn.classList.remove("d-none"); // 显示签退按钮
    }
  }
  if (stat.signout_time) {
    const dt = new Date(stat.signout_time * 1000);
    const hours = String(dt.getHours()).padStart(2, "0");
    const minutes = String(dt.getMinutes()).padStart(2, "0");
    const seconds = String(dt.getSeconds()).padStart(2, "0");

    const formatted = `已签退 - ${hours}:${minutes}:${seconds}`;
    signout_btn.textContent = formatted;
    signout_btn.disabled = true; // 禁用签退按钮
  }
}

document.addEventListener("DOMContentLoaded", async function () {
  // 获取cookie中的access_token
  const access_token = document.cookie
    .split("; ")
    .find((row) => row.startsWith("access_token="))
    ?.split("=")[1];
  console.log("Access Token:", access_token);
  // 检查access_token是否存在
  if (access_token) {
    // await GetUserInfo(access_token);
    await GetSignStat(access_token);
  } else {
    alert("Token过期或未登录，请重新登录");
    // 清除cookie中的access_token
    window.location.href = "/index.html"; // 如果没有登录，重定向到登录页面
  }
  InitHeader(); // 初始化头部
});

function updateDateTime() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");

  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

  document.getElementById(
    "current-date-time"
  ).textContent = `当前时间：${formatted}`;
}

// 页面加载后立即调用一次，避免延迟1秒
updateDateTime();
// 每秒更新一次时间
setInterval(updateDateTime, 1000);


window.SigninFunc = SigninFunc;
window.SignoutFunc = SignoutFunc;